package threadimpl;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class ThreadCallable {
    public static void main(String[] args) {
        // 创建callable实现类的对象
        MyThread3 mt1 = new MyThread3();
        // 传参数
        mt1.setLength(100);
        // 将此callable实现类的对象作为参数传递到FutureTask的构造器中，创建FutureTask对象
        FutureTask<Integer> integerFutureTask = new FutureTask<>(mt1);
        // 将FutureTask作为参数传递Thread构造器中，创建Thread对象，并调用start方法
        new Thread(integerFutureTask).start();

        try{
            // 获取Callable中call方法中的返回值
            // get()返回值即为futureTask构造器参数Callable实现类重写的call的返回值
            Integer sum = integerFutureTask.get();
            System.out.println("总计：" + sum);
        }catch (InterruptedException e){
            e.printStackTrace();
        }catch (ExecutionException e){
            e.printStackTrace();
        }
    }
}


class MyThread3 implements Callable<Integer>{

    private int length;

    public void setLength(int length){
        this.length = length;
    }

    @Override
    public Integer call() throws Exception {
        int sum = 0;
        for (int i=0; i<=length; i++){
            if(i%2 ==0){
                sum +=i;
            }
        }
        return sum;
    }
}